package com.app.db;

import java.sql.Connection;
import java.sql.SQLException;

import com.app.config.DCacheConfig;
import com.app.exception.DCacheException;

import com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;


public class DBPool {
	private BoneCP connectionPool;
	private static DBPool instance= new DBPool();
	private DBPool(){
		this.initDbConnections();
	}
	
	public static DBPool getInstance() {
		return instance;
	}
	
	private void initDbConnections(){
		//读取配置文件
		DCacheConfig dcfg = DCacheConfig.getInstance();
		try {
            String url = "jdbc:mysql://%s:%d/%s?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false&maxReconnects=10";
            BoneCPConfig config = new BoneCPConfig();
            config.setJdbcUrl(String.format(url, dcfg.getDatabaseIP(),
                    dcfg.getDatabasePort(), dcfg.getDatabaseName()));
            config.setUsername(dcfg.getDatabaseUser());
            config.setPassword(dcfg.getDatabasePassword());
            config.setMinConnectionsPerPartition(dcfg.getDatabaseInitConn());
            config.setMaxConnectionsPerPartition(dcfg.getDatabaseMaxConn());
            config.setPartitionCount(dcfg.getPartitionCount());//设置分区 
            config.setLazyInit(false);
            config.setConnectionTimeoutInMs(10000);//超时时间
            connectionPool = new BoneCP(config);
            //http://blog.chinaunix.net/uid-26706281-id-3079202.html
        } catch (SQLException e) {
				throw new DCacheException(e.getMessage(),e);
			}
        }
	public Connection getConnection() throws SQLException{
		return connectionPool.getConnection();
	}
	
	public void close() {
		connectionPool.close();
		connectionPool.shutdown();
	}
	
	public static void main(String[] args) throws Exception {
	}
	
	
}
